﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using Lib.Utils;

namespace MS.INV.Sales
{
    public partial class Edit_Sale : Lib.Bases.Forms.BaseForm
    {
        SysObj.Bh_BanHang bh = new SysObj.Bh_BanHang();

        public int OrderID { get; set; }
        public bool SaveChanged { get; set; }

        DataTable PopupData = new DataTable();
        bool bLock = false;

        public Edit_Sale()
        {
            InitializeComponent();
        }

        protected override void  OnHandleDestroyed(EventArgs e)
        {
            bh.Dispose();
 	        base.OnHandleDestroyed(e);
        }

        private void Edit_Sale_Load(object sender, EventArgs e)
        {
            LoadData();
        }

        private void LoadData()
        {
            if (OrderID > 0)
            {
                bh.IdBanHang = OrderID;
                bh.LoadData();

                using (SysObj.L_HangHoa hh = new SysObj.L_HangHoa())
                {
                    PopupData = hh.ListMenu();
                    repPro.SetDataSource(PopupData, "MaHang,TenHang#Mã,Tên");
                }

                using (SysLst.L_Ban b = new SysLst.L_Ban())
                {
                    b.LoadData(bh.IdBan);
                    lbl.Text = b.TenBan;
                }

                barDate.EditValue = bh.Ngay;

                txtSubTotal.Text = bh.ThanhTien.ToString("n2");
                nuDiscountPercent.Value = bh.PT_CK;
                txtDiscountValue.Text = bh.Tien_CK.ToString("n2");
                txtTotal.Text = bh.TongTien.ToString("n2");
                txtNotes.Text = bh.GhiChu;
                nuPayment.Value = bh.KhachTra;

                grid.DataSource = bh.GetDetail();

                using (SysObj.Bh_BanHang_GopBan mer = new SysObj.Bh_BanHang_GopBan())
                {
                    LoadMergeItem(mer.LoadMergeItemByID(bh.IdBanHang));
                }
            }
        }

        private void LoadMergeItem(DataTable DataMerge)
        {
            pnlMergeItem.Controls.Clear();

            if (DataMerge != null && DataMerge.Rows.Count > 0)
            {
                pnlMergeItem.Visible = false;
                if (DataMerge.Rows.Count == 1 && ToDecimal(DataMerge.Rows[0]["IdBanHang"]) == OrderID)
                    return;
                foreach (DataRow row in DataMerge.Rows)
                {
                    pnlMergeItem.Controls.Add(GetLabel(ToDecimal(row["IdBanHang"]), row["TenBan"].ToString()));
                }

                pnlMergeItem.Controls.Add(GetLabel(
                    "_" + ToDecimal(DataMerge.Rows[0]["IdBanHang"]).ToString(), "Tổng"));

                pnlMergeItem.Visible = true;
            }
        }

        private LinkLabel GetLabel(object Tag, string TblNum)
        {
            LinkLabel _lbl = new LinkLabel();
            _lbl.AutoSize = false;
            _lbl.Width = 50;
            _lbl.Font = new System.Drawing.Font(_lbl.Font.Name, 9F, FontStyle.Bold);
            _lbl.Dock = DockStyle.Left;
            _lbl.TextAlign = ContentAlignment.MiddleCenter;
            _lbl.Click += new EventHandler(_lbl_Click);
            _lbl.MouseUp += new MouseEventHandler(_lbl_MouseUp);
            _lbl.Tag = Tag;
            _lbl.Text = TblNum;
            _lbl.BringToFront();

            return _lbl;
        }

        void _lbl_MouseUp(object sender, MouseEventArgs e)
        {
            LinkLabel _lbl = (LinkLabel)sender;
            if (Cvert.ToString(_lbl.Tag, "").Substring(0, 1) == "_")
                return;

            if (e.Button == System.Windows.Forms.MouseButtons.Right)
                popGroupDetail.ShowPopup(Cursor.Position);
        }

        void _lbl_Click(object sender, EventArgs e)
        {
            LinkLabel lbl = (LinkLabel)sender;

            bLock = false;
            OrderID = (int)ToDecimal(Cvert.ToString(lbl.Tag, "").Replace("_", ""));

            if (Cvert.ToString(lbl.Tag, "").Substring(0, 1) == "_")
            {
                LoadSummary();
                bLock = true;
            }
            else
                LoadData();

            ResetLock();
        }

        private void LoadSummary()
        {
            using (SysObj.Bh_BanHang bh = new SysObj.Bh_BanHang())
            {
                grid.DataSource = bh.GetSummary(OrderID);
                barDate.EditValue = bh.Ngay;
                txtSubTotal.Text = bh.ThanhTien.ToString("n2");
                nuDiscountPercent.EditValue = bh.PT_CK;
                txtDiscountValue.Text = bh.Tien_CK.ToString("n2");
                txtTotal.Text = bh.TongTien.ToString("n2");
                nuPayment.EditValue = bh.KhachTra;
                txtNotes.Text = bh.GhiChu;
                using (SysObj.Bh_BanHang_GopBan mer = new SysObj.Bh_BanHang_GopBan())
                {
                    LoadMergeItem(mer.LoadMergeItemByID(bh.IdBanHang));
                }
            }
        }

        private void ResetLock()
        {
            view.OptionsBehavior.ReadOnly = bLock;
            nuDiscountPercent.Properties.ReadOnly = bLock;
            txtNotes.Properties.ReadOnly = bLock;
            btDel.Enabled = !bLock;
        }

        private void view_CellValueChanged(object sender, DevExpress.XtraGrid.Views.Base.CellValueChangedEventArgs e)
        {
            btUp.Enabled = true;

            if (e.Column.FieldName.ToLower() == "dongia" || e.Column.FieldName.ToLower() == "soluong" ||
                e.Column.FieldName.ToLower() == "pt_ck")
            {
                DataRow row = view.GetFocusedDataRow();
                if (!object.Equals(row, null))
                    CalcRow(row);
            }
            else if (e.Column.FieldName.ToLower() == "idhanghoa")
            {
                DataRow row = view.GetFocusedDataRow();
                if (IsExists(Convert.ToInt32(row["IdHangHoa"])))
                {
                    MessageBox.Show("Thực đơn này đã tồn tại, vui lòng chọn thực đơn khác.", "Thông báo.",
                        MessageBoxButtons.OK, MessageBoxIcon.Error);
                    return;
                }

                DataRow[] rS = PopupData.Select("IdHangHoa =" + row["IdHangHoa"].ToString());
                if (!object.Equals(rS, null) && rS.Length > 0)
                {
                    row["TenHang"] = rS[0]["TenHang"];
                    row["TenDVT"] = rS[0]["TenDVT"];
                    row["SoLuong"] = 1;
                    row["DonGia"] = rS[0]["DonGia"];
                    view.UpdateCurrentRow();
                    CalcRow(row);
                }
            }
        }

        private void CalcRow(DataRow row)
        {
            row["ThanhTien"] = ToDecimal(row["SoLuong"]) * ToDecimal(row["DonGia"]);
            row["Tien_CK"] = ToDecimal(row["ThanhTien"]) * ToDecimal(row["PT_CK"]) / 100;
            row["TongTien"] = ToDecimal(row["ThanhTien"]) - ToDecimal(row["Tien_CK"]);
            view.PostEditor();

            SumTotal();
        }

        private void SumTotal()
        {
            DataTable Detail = (DataTable)grid.DataSource;
            if (Detail != null && Detail.Rows.Count > 0)
            {
                decimal sub = 0;
                foreach (DataRow row in Detail.Rows)
                    sub += ToDecimal(row["TongTien"]);
                txtSubTotal.Text = sub.ToString("n2");
                txtDiscountValue.Text = (sub * nuDiscountPercent.Value / 100).ToString("n2");
                txtTotal.Text = (sub - ToDecimal(txtDiscountValue.Text)).ToString("n2");
            }
        }

        private bool IsExists(int ProductID)
        {
            DataTable table = grid.DataSource as DataTable;
            DataRow[] rS = table.Select("IdHangHoa=" + ProductID);
            if (!object.Equals(rS, null) && rS.Length > 0) return true;
            return false;
        }

        private decimal ToDecimal(object value)
        {
            try
            {
                return Convert.ToDecimal(value);
            }
            catch
            {
                return 0;
            }
        }

        private void btUp_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            try
            {
                if (ToDecimal(nuPayment.EditValue) > 0 && ToDecimal(nuPayment.EditValue) < ToDecimal(txtTotal.Text))
                {
                    MessageBox.Show("Số tiền khách thanh toán không thể nhỏ hơn tổng số tiền cần thanh toán.", "Thông báo.",
                        MessageBoxButtons.OK, MessageBoxIcon.Error);
                    return;
                }

                if (bLock)// Is summary
                {
                    bh.UpdateSummary(OrderID);
                    SaveChanged = true;
                    return;
                }

                view.PostEditor();
                view.UpdateCurrentRow();

                DataTable DT = (DataTable)grid.DataSource;
                if (DT != null) DT.AcceptChanges();

                bh.Ngay = Convert.ToDateTime(barDate.EditValue);

                bh.ThanhTien = ToDecimal(txtSubTotal.Text);
                bh.PT_CK = (int)nuDiscountPercent.Value;
                bh.Tien_CK = ToDecimal(txtDiscountValue.Text);
                bh.KhachTra = nuPayment.Value;
                bh.TongTien = ToDecimal(txtTotal.Text);
                bh.GhiChu = txtNotes.Text;
                bh.D_HH = DT;
                bh.OnUpdate();

                btUp.Enabled = false;
                SaveChanged = true;
            }
            catch(Exception ex)
            {
                Lib.Bases.SysError.RaiseError(ex, this.Name, "Save data");
            }
        }

        private void btPrint_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            DataTable DTT = new DataTable();
            using (SysObj.Bh_BanHang bh = new SysObj.Bh_BanHang())
                DTT = bh.GetDataPrint(OrderID);
            Lib.Bases.Reports.ShowReport("Bill.repx", DTT, "TenQuan,DiaChi", Systems.Options.TenQuan, Systems.Options.DiaChi);
        }

        private void btDel_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            if (MessageBox.Show("Bạn có chắc chắn xóa bỏ dữ liệu của bàn này hay không ?", "Xác nhận.",
                        MessageBoxButtons.YesNo, MessageBoxIcon.Warning) == DialogResult.No)
            {
                return;
            }

            using (SysObj.Bh_BanHang bh = new SysObj.Bh_BanHang())
            {
                bh.IdBanHang = OrderID;
                bh.OnDelete();
                SaveChanged = true;
            }
        }

        private void btBack_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            this.Close();
        }

        private void txtNotes_TextChanged(object sender, EventArgs e)
        {
            btUp.Enabled = true;
        }

        private void nuDiscountPercent_EditValueChanged(object sender, EventArgs e)
        {
            btUp.Enabled = true;
        }

        private void barDate_EditValueChanged(object sender, EventArgs e)
        {
            btUp.Enabled = true;
        }

        private void barUnGroup_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            if (MessageBox.Show("Bạn có chắc chắn muôn bỏ bàn này ra khỏi nhóm đã gộp hay không ?", "Xác nhận.",
                        MessageBoxButtons.YesNo, MessageBoxIcon.Warning) == DialogResult.No)
            {
                return;
            }
            using (SysObj.Bh_BanHang_GopBan gop = new SysObj.Bh_BanHang_GopBan())
            {
                gop.UnMerge(OrderID);
            }
            LoadData();
        }
    }
}
